package top.eggcode.modules.user.service;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.eggcode.modules.user.model.PowerEntity;
import top.eggcode.modules.user.model.rolePowerEntity;
import top.eggcode.modules.user.store.PowerStore;
import top.eggcode.modules.user.store.RolePowerRepository;
import top.eggcode.base.BaseServiceImpl;

import java.util.LinkedList;
import java.util.List;

/**
 * Title:
 * Description: TODO
 * Date: 2021/8/7 22:37
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@Service
public class RolePowerService extends BaseServiceImpl<rolePowerEntity> {

    private final RolePowerRepository rolePowerRepository;

    private final PowerStore powerStore;

    /**
     * 查找列表
     *
     * @param roleId 角色id
     * @return 授权
     */
    public List<PowerEntity> listPower(String roleId) {
        List<rolePowerEntity> relationList = rolePowerRepository.findByRoleId(roleId);
        List<PowerEntity> powerList = new LinkedList<>();
        relationList.forEach(relation -> {
            powerStore.findById(relation.getPowerId()).ifPresent(powerList::add);
        });
        return powerList;
    }

    public void clearPowers(String roleId) {
        rolePowerRepository.batchDeleteByRole(roleId);
    }

}
